import axios from 'axios'
import {
  Toast
} from 'vant'
import store from '@/store'
import Qs from 'qs';
let loading
let message = '加载中...'

function startLoading() {
  loading = Toast.loading({
    message: message,
    forbidClick: true,
    duration: 0,
  })
}

function endLoading() {
  loading.clear()
}
// axios.defaults.headers.common['Authorization'] = store.state.token;
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: '', // request timeout,
  headers: {
    "Content-Type": "application/json"
  },
  params:{},
  transformRequest: [function (data) {
    // 增加token
    let newData = {
      ...data
    };
    return JSON.stringify(newData)
    if (newData.isFormData) {

      delete newData.isFormData

      let formData = new FormData()
      Object.keys(newData).forEach(key => {
        formData.append(key, newData[key])
      })
      return formData;
      // return Qs.stringify(data);

    } else {
      return JSON.stringify(newData);
    }
  }], // 设置固定参数
})
service.interceptors.request.use(
  config => {
    config.headers['token'] = store.state.token
    message = '加载中...'
    if (config.data && JSON.stringify(config.data).indexOf('80301')>0) {
      // console.log('=====code-80301，不显示toast');
    } else {
      startLoading();
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
service.interceptors.response.use(
  response => {
    if (loading) {
      endLoading();
    }
    const res = response.data
    if (res.errorCode == '9997' || res.retCode == '2004') {
      store.dispatch('set_userToken', '')
      loginReload() //接口ok后打开注释
    } else if (res.retCode != 0) {
        Toast(res.retMessage || '请求失败，请重试～')
        return Promise.reject(res.retMessage || 'Error')
    } else {
      return res
    }
    // else if (res.errorCode != '0') {
    //   if(response.request.responseURL.indexOf('oauth')){
    //     // loginReload()
    //     return
    //   }
    //   Toast(res.errorMessage)
    //   return Promise.reject(res.errorMessage || 'Error');
    // }
  },
  error => {
    Toast(error.retMessage || '请求失败，请重试～')
    return Promise.reject(error)
  }
)

function loginReload() {
  const appId = 'wx36b31857f8d20a72'
  const scope = 'snsapi_base'
  const urlState = 'Citics600030'
  const agentId = '1000238'
  const wxcode = "023451"
  // const wxcode = "0123456"

  let redirectUrl, openUrl
  redirectUrl = encodeURIComponent(window.location.href)
  openUrl =
    `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUrl}&response_type=code&scope=${scope}&state=${urlState}agentid=${agentId}#wechat_redirect`
  window.location.href = openUrl
}

export default service